<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','grade','tele','truename','last_at'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function setPasswordAttribute($password)
    {
        if (Hash::needsRehash($password)) {
            $this->attributes['password'] = Hash::make($password);
        }

    }
    public function clubroleid(){
        //知道管理员权限对应的俱乐部id
        $club_id = substr($this->roles->first()->name,0,stripos($this->roles->first()->name,'_'));
        return $club_id;
    }
    public function clubmodelforrole(){
        $club_id = substr($this->roles->first()->name,0,stripos($this->roles->first()->name,'_'));
        return Club::find($club_id);
    }
    public function clubrolename(){
        if($this->roles->first()->name =='root_admin'){
            return '全局管理员';
        }
        $club_id = substr($this->roles->first()->name,0,stripos($this->roles->first()->name,'_'));
        return Club::find($club_id)->name;
    }
    public function owns($model)
    {

        $club_id = substr($this->roles->first()->name,0,stripos($this->roles->first()->name,'_'));
        if($model instanceof Club){
            return $club_id==$model->id;
        }
        return $club_id ==$model->club->id;
    }
    public function roles(){
        return $this->belongsToMany(Role::class);
    }

    public function giveRole(Role $role){
        return $this->roles()->save($role);
    }

    public function hasRole($role){
        if(is_string($role)){
            return $this->roles->contains('name',$role);
        }
        return !! $role->intersect($this->roles)->count();
    }
    public function keytodata($keyname){
        return collect($keyname)->map(function($key){
            if(  !is_string($this->$key) && !is_int($this->$key)){
                if(  $this->$key  instanceof Carbon){
                    return [$key=>$this->$key->toFormattedDateString()];
                }
                else{
                    return [$key=>$this->$key->pluck('label')];
                }

            }

            return [$key=>$this->$key];
        })->collapse()->toArray();



    }
}
